package com.kakarote.hrm.task;

import cn.hutool.core.util.StrUtil;
import com.kakarote.hrm.entity.PO.HrmEmployee;
import com.kakarote.hrm.service.impl.HrmEmployeeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @Author 92487
 * @Date 2024/10/20 15:39
 */
@Component
@EnableScheduling
@EnableAsync
@Slf4j
public class EmployeeTask {

    @Autowired
    private HrmEmployeeServiceImpl employeeService;

    @Scheduled(cron = "0 0 4 * * ? ")
    public void employeeAgeUpdateTask() {
        List<HrmEmployee> list = employeeService.lambdaQuery().eq(HrmEmployee::getIsDel, 0).list();

        if (list != null && !list.isEmpty()) {
            list.forEach(employee -> {
                //根据身份证计算年龄
                String idNumber = employee.getIdNumber();
                if (StrUtil.isNotBlank(idNumber)){
                    Integer i = calculateAgeByIdNumber(idNumber);
                    employeeService.lambdaUpdate().set(HrmEmployee::getAge, i).eq(HrmEmployee::getEmployeeId, employee.getEmployeeId()).update();
                }
            });
        }
    }

    public Integer calculateAgeByIdNumber(String idNumber) {
        if (idNumber == null || idNumber.length() != 18) {
            return -1; // 身份证号码无效
        }

        // 提取出生日期
        String birthStr = idNumber.substring(6, 14); // 假设身份证号码格式正确

        // 格式化出生日期和当前日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            Date birthDate = sdf.parse(birthStr);
            Calendar birthCalendar = Calendar.getInstance();
            birthCalendar.setTime(birthDate);

            Calendar nowCalendar = Calendar.getInstance();

            // 计算年龄
            Integer age = nowCalendar.get(Calendar.YEAR) - birthCalendar.get(Calendar.YEAR);
            if (nowCalendar.get(Calendar.MONTH) < birthCalendar.get(Calendar.MONTH) ||
                    (nowCalendar.get(Calendar.MONTH) == birthCalendar.get(Calendar.MONTH) &&
                            nowCalendar.get(Calendar.DAY_OF_MONTH) < birthCalendar.get(Calendar.DAY_OF_MONTH))) {
                age--;
            }

            return age;
        } catch (ParseException e) {
            // 日期格式错误
            e.printStackTrace();
            return null;
        }
    }
}
